package com.sinosoft.brokerchannel.server;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.sinosoft.brokerchannel.base.common.SystemParamFinal;
import com.sinosoft.brokerchannel.base.server.LogService;
import com.sinosoft.brokerchannel.base.utile.BusinessException;
import com.sinosoft.brokerchannel.base.utile.ToolUtils;
import com.sinosoft.brokerchannel.entity.vo.*;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @需求名称:图片云存储管理
 * @类描述:图片云存储的service
 */
@Service
public class ImageCloudStorageService {
    @SuppressWarnings("restriction")
    private static final sun.misc.BASE64Decoder b64d = new sun.misc.BASE64Decoder();
    @SuppressWarnings("restriction")
    private static final sun.misc.BASE64Encoder b64e = new sun.misc.BASE64Encoder();
    private static final XStream xs = new XStream();

    static {
        xs.processAnnotations(Content.class);
    }

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final DateFormat dft = new SimpleDateFormat("yyyyMMddHHmmss");
    @Autowired
    private LogService logService;
    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
    private AppImageCloudStorageService appImageCloudStorageService;

    /**
     * @param request {@link ImageCloudStorageRequest}
     * @return 操作成功的信息 {@link ImageCloudStorageResponse}
     * @throws BusinessException
     * @需求名称：图片云存储
     * @描述:图片云存储的核心方法，对图片的操作：1、上传 2、下载 3、删除
     */
    public ImageCloudStorageResponse imageCloudStorage(ImageCloudStorageRequest request) throws BusinessException {
        ImageCloudStorageResponse response = new ImageCloudStorageResponse();
        ImageCloudStorageResponseMain responseBody = new ImageCloudStorageResponseMain();
        try {
            String actionType = "";//操作类型
            //获取请求信息
            List<ImageVO> imageList = request.getRequestBody().getArrayOfImageVO().getImageList();
            String systemCode = request.getRequestBody().getSystemCode();
            for (ImageVO imageVO : imageList) {
                actionType = imageVO.getActionType();
                if ((SystemParamFinal.IMAGE_UPLOAD).equals(actionType)) {//上传
                    this.imageUpload(systemCode, imageVO, request);
                } else if ((SystemParamFinal.IMAGE_DOWNLOAD).equals(actionType)) {//下载
                    this.imageDownload(imageVO);
                } else if ((SystemParamFinal.IMAGE_DELETE).equals(actionType)) {//删除
                    this.imageDelete(imageVO);
                }
                appImageCloudStorageService.storage(imageVO);//记录日志
            }
            responseBody.setImageList(imageList);
        } catch (BusinessException e) {//影像系统上传失败未抛出异常, 导致前端以为上传成功, 后续流程报错.
            logger.info(SystemParamFinal.Exception_LOG, e);//影像系统上传失败未抛出异常, 导致前端以为上传成功, 后续流程报错.
            throw e;//影像系统上传失败未抛出异常, 导致前端以为上传成功, 后续流程报错.
        } catch (Exception e) {
            logger.info(SystemParamFinal.Exception_LOG, e);
        } finally {
            response.setResponseBody(responseBody);
        }
        return response;
    }

    /**
     * @param imageVO ({@link ImageVO})
     * @param request ({@link ImageCloudStorageRequest})
     * @throws BusinessException
     * @需求名称：图片云存储管理
     */
    @SuppressWarnings("restriction")
    private void imageUpload(String systemCode, ImageVO imageVO, ImageCloudStorageRequest request) throws BusinessException {
        Content content = null;
        String channelCode = request.getRequestBody().getChannel().getChannelCode();//渠道码
        String reqXml = "";//请求业务参数
        String resXml = "";//返回业务参数
        String impageContent = "";//图片信息
        String status = "";//状态
        try {
            //组织图片上传请求数据
            try {
                content = new Content();
                content.setTransactionId(dft.format(new Date(System.currentTimeMillis())));//时间戳到毫秒
                content.setName(systemConfigService.getProperty("imagecloudstorage_name"));//渠道名称
                content.setCode(systemConfigService.getProperty("imagecloudstorage_code"));//渠道代码
                content.setPwd(systemConfigService.getProperty("imagecloudstorage_pwd"));//渠道密码
                reqXml = xs.toXML(content);
                logService.stringPrint("图片上传请求数据", reqXml);
            } catch (Exception e) {
                logger.info(SystemParamFinal.Exception_LOG, e);
                throw new BusinessException(SystemParamFinal.BUSINESS_EXCEPTION_0034, "组织图片上传请求数据异常");
            }
            //进行图片上传
            try {
                impageContent = imageVO.getImageContent();
                impageContent = URLDecoder.decode(impageContent, "UTF-8");
                byte[] bt = null;
                bt = b64d.decodeBuffer(impageContent);
                //resXml = photoService.UploadPhotof(reqXml, bt);
                Date date = new Date();
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String dateStr = df.format(date);
                Random random = new Random();
                int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;
                resXml = "<Content><transactionid>" + dateStr + "</transactionid><rsptime>2018-08-09 16:56:55</rsptime><status>0</status><rspdesc>成功</rspdesc><fileid>63e63825-a8e4-4e18-b273-bdeeda2" + String.valueOf(rannum) + "</fileid><downloadurl>http://prodanswer-10004517.image.myqcloud.com/63e63825-a8e4-4e18-b273-bdeeda255857</downloadurl><url>http://web.image.myqcloud.com/photos/v2/10004517/prodanswer/0/63e63825-a8e4-4e18-b273-bdeeda255857</url></Content>";
                String imageType = imageVO.getImgName();
                String newPath = "D:/" + dft.format(new Date(System.currentTimeMillis())) + "." + imageType;
                System.out.println(newPath);
                uploadFolder(newPath, bt);
                if (resXml == null || "".equals(resXml)) {
                    throw new BusinessException(SystemParamFinal.BUSINESS_EXCEPTION_0034, "云存储返回为空！");
                }
            } catch (Exception e) {
                logger.info(SystemParamFinal.Exception_LOG, e);
                throw new BusinessException(SystemParamFinal.BUSINESS_EXCEPTION_0034, "图片上传异常！");
            }
            //对图片上传返回结果进行保存
            content = ToolUtils.xml2obj(Content.class,resXml);


//            content = (Content) xs.fromXML(resXml);
            status = content.getStatus();
            imageVO.setStatus(status);//状态编码
            imageVO.setResponseMessag(content.getRspDesc());//响应信息
            imageVO.setImageContent("");//清空图片内容，减少输出内容
            //AnswernImageUploadResult returnStr = new AnswernImageUploadResult();
            if ("0".equals(status)) {//成功
                imageVO.setFileId(content.getFileId());//文件id
                imageVO.setDownloadUrl(content.getDownloadUrl());//下载的url
                imageVO.setUrl(content.getUrl());//文件存储的url
                //调用核心影像接口保存图片上传信息 -  Map<String, String> SaveUploadfile(List<PlyImgIdxVO> paramList)
                //车险系统
                if ((imageVO.getcAppNo() != null || imageVO.getcPlyNo() != null) && !"EC17060049".equals(channelCode)) {
                    List<PlyImgIdxVO> paramList = new ArrayList<>();
                    PlyImgIdxVO plyImgIdxVO = new PlyImgIdxVO();
                    plyImgIdxVO.setCPlyNo(imageVO.getcPlyNo());//保单号
                    plyImgIdxVO.setCAppNo(imageVO.getcAppNo());//投保单号
                    plyImgIdxVO.setCImgTyp(imageVO.getcImgTyp());//影像类型
                    plyImgIdxVO.setCImgFileNme(content.getDownloadUrl());//影像文件名(万象有图路径)
                    plyImgIdxVO.setCImgDesc(content.getFileId());//影像描述（文件名称）
                    plyImgIdxVO.setCAppTyp(imageVO.getcAppTyp());//申请类型
                    plyImgIdxVO.setCStatus("0");//有效状态 0 有效， 1 无效
                    plyImgIdxVO.setCTarget("");//上传标志
                    paramList.add(plyImgIdxVO);
                    //this.resultDecision(iSaveUploadfileApi_vhl.SaveUploadfile(paramList));
                }

            } else {//失败
                imageVO.setResponseMessag(content.getRspDesc());//状态
                throw new BusinessException("ImageCloudStorageService-0000", "影像系统返回提示: " + content.getRspDesc());//影像系统上传失败未抛出异常, 导致前端以为上传成功, 后续流程报错.
            }
        } catch (BusinessException e) {
            e.printStackTrace();
            logger.info(SystemParamFinal.Exception_LOG, e);//影像系统上传失败未抛出异常, 导致前端以为上传成功, 后续流程报错.
            throw e;//影像系统上传失败未抛出异常, 导致前端以为上传成功, 后续流程报错.
        } catch (Exception e) {
            logger.info(SystemParamFinal.Exception_LOG, e);
            imageVO.setStatus(SystemParamFinal.IMAGE_UPLOAD);
            imageVO.setResponseMessag("图片上传失败，请求联系接口开发人员！");
        }
    }

    /**
     * @param imageVO({@link ImageVO})
     * @throws BusinessException
     * @需求名称：图片云存储管理
     * @描述:图片下载
     */
    @SuppressWarnings("restriction")
    private void imageDownload(ImageVO imageVO) {
        Content content = null;
        String reqXml = "";//请求业务参数
        String resXml = "";//返回业务参数
        String imageContent = "";//图片信息
        byte[][] bts = null;
        byte[] bt = null;
        String status = "";
        try {
            try {
                content = new Content();
                content.setTransactionId(dft.format(new Date(System.currentTimeMillis())));//时间戳到毫秒
                content.setName(systemConfigService.getProperty("imagecloudstorage_name"));//渠道名称
                content.setCode(systemConfigService.getProperty("imagecloudstorage_code"));//渠道代码
                content.setPwd(systemConfigService.getProperty("imagecloudstorage_pwd"));//渠道密码
                content.setDownloadUrl(imageVO.getDownloadUrl());//下载url
                reqXml = xs.toXML(content);
                logService.stringPrint("图片下载请求数据", reqXml);
            } catch (Exception e) {
                logger.info(SystemParamFinal.Exception_LOG, e);
                throw new BusinessException(SystemParamFinal.BUSINESS_EXCEPTION_0034, "组织图片下载请求数据异常");
            }
            try {
                // bts = photoService.DownLoadPhoto(reqXml);
                if (bts == null || bts.length == 0) {
                    throw new BusinessException(SystemParamFinal.BUSINESS_EXCEPTION_0034, "图片下载返回数据为空！");
                }
                bt = bts[0];
                resXml = new String(bt);
                logService.stringPrint("图片上传返回数据", resXml);
                if ("".equals(resXml)) {
                    throw new BusinessException(SystemParamFinal.BUSINESS_EXCEPTION_0034, "云存储返回为空！");
                }
            } catch (BusinessException e) {
                logger.info(SystemParamFinal.Exception_LOG, e);
                throw e;
            } catch (Exception e) {
                logger.info(SystemParamFinal.Exception_LOG, e);
                throw new BusinessException("0034", "图片下载异常！");
            }
            content = (Content) xs.fromXML(resXml);
            status = content.getStatus();
            imageVO.setStatus(status);//状态编码
            imageVO.setResponseMessag(content.getRspDesc());//状态
            if ("0".equals(status)) {
                bt = bts[1];
                imageContent = b64e.encode(bt);//使用base64encoder把字节数组转换成base64编码的字符串
                imageContent = URLEncoder.encode(imageContent, "UTF-8");
                imageVO.setImageContent(imageContent);//图片信息
            }
        } catch (BusinessException e) {
            logger.info(SystemParamFinal.Exception_LOG, e);
            imageVO.setStatus("1");
            imageVO.setResponseMessag(e.getExceptionMessage());
        } catch (Exception e) {
            logger.info(SystemParamFinal.Exception_LOG, e);
            imageVO.setStatus("1");
            imageVO.setResponseMessag("图下载传失败，请求联系接口开发人员！");
        }
    }

    /**
     * @param imageVO({@link ImageVO})
     * @throws BusinessException
     * @需求名称：图片云存储管理
     * @描述:图片删除
     */
    private void imageDelete(ImageVO imageVO) {
        Content content = null;
        String reqXml = "";//请求业务参数
        String resXml = "";//返回业务参数
        try {
            try {
                content = new Content();
                content.setTransactionId(dft.format(new Date(System.currentTimeMillis())));//时间戳到毫秒
                content.setName(systemConfigService.getProperty("imagecloudstorage_name"));//渠道名称
                content.setCode(systemConfigService.getProperty("imagecloudstorage_code"));//渠道代码
                content.setPwd(systemConfigService.getProperty("imagecloudstorage_pwd"));//渠道密码
                content.setFileId(imageVO.getFileId());//云端存储的图片文件ID
                reqXml = xs.toXML(content);
                logService.stringPrint("图片上删除求数据", reqXml);
            } catch (Exception e) {
                logger.info(SystemParamFinal.Exception_LOG, e);
                throw new BusinessException("0034", "组织图片删除请求数据异常");
            }
            try {
                //resXml = photoService.DeletePhoto(reqXml);
                resXml = "<Content><transactionid>20180809171208</transactionid><rsptime>2018-08-09 17:12:18</rsptime><status>0</status><rspdesc>成功</rspdesc></Content>";
                logService.stringPrint("图片删除返回数据", resXml);
                if (resXml == null || "".equals(resXml)) {
                    throw new BusinessException("0034", "云存储返回为空！");
                }
            } catch (Exception e) {
                logger.info(SystemParamFinal.Exception_LOG, e);
                throw new BusinessException("0034", "图片删除异常！");
            }
            //影响删除wangxiaodong
            Map<String, String> map = null;
            content = (Content) xs.fromXML(resXml);
            List<PlyImgIdxVO> paramList = new ArrayList<PlyImgIdxVO>();
            PlyImgIdxVO plyImgIdxVO = new PlyImgIdxVO();
            plyImgIdxVO.setCPlyNo(imageVO.getcPlyNo());//保单号
            plyImgIdxVO.setCAppNo(imageVO.getcAppNo());//投保单号
            plyImgIdxVO.setCImgTyp(imageVO.getcImgTyp());//影像类型
            plyImgIdxVO.setCImgFileNme(imageVO.getDownloadUrl());//影像文件名(万象有图路径)
            plyImgIdxVO.setCImgDesc(imageVO.getFileId());
            ;//影像描述（文件名称）
            plyImgIdxVO.setCAppTyp(imageVO.getcAppTyp());//申请类型
            //plyImgIdxVO.setCImgId(content.);
            plyImgIdxVO.setCStatus("1");//有效状态 0 有效， 1 无效
            plyImgIdxVO.setCTarget("");//上传标志

            paramList.add(plyImgIdxVO);
            //map = iSaveUploadfileApi_vhl.SaveUploadfile(paramList);
            map.put("SuccessSign", "1");
            if (map != null) {
                String savaStatus = map.get("SuccessSign");//1：成功；2：失败
                if ("2".equals(savaStatus)) {
                    throw new BusinessException("0034", "调用核心服务删除图片上传信息失败:" + map.get("ErrorMsg"));
                }
            } else {
                throw new BusinessException("0034", "调用核心服务图片删除信息失败！");
            }

            imageVO.setStatus(content.getStatus());//状态编码
            imageVO.setResponseMessag(content.getRspDesc());//状态
        } catch (BusinessException e) {
            logger.info(SystemParamFinal.Exception_LOG, e);
            imageVO.setStatus("1");
            imageVO.setResponseMessag(e.getExceptionMessage());
        } catch (Exception e) {
            logger.info(SystemParamFinal.Exception_LOG, e);
            imageVO.setStatus("1");
            imageVO.setResponseMessag("图片删除失败，请联系接口开发人员！");
        }
    }

    /**
     * 调用Dubbo结果处理
     *
     * @param map
     */
    private void resultDecision(Map<String, String> map) throws BusinessException {
        if (map != null) {
            String savaStatus = map.get("SuccessSign");//1：成功；2：失败
            if ("2".equals(savaStatus)) {
                throw new BusinessException(SystemParamFinal.BUSINESS_EXCEPTION_0034, "调用核心服务保存图片上传信息失败:" + map.get("ErrorMsg"));
            }
        } else {
            throw new BusinessException(SystemParamFinal.BUSINESS_EXCEPTION_0034, "调用核心服务保存图片上传信息失败！");
        }
    }

    /**
     * xml报文转换工具类
     *
     * @author Administrator
     */
    @XStreamAlias("Content")
    @Data
    private static class Content {
        @JsonProperty("transactionid")
        @XStreamAlias("transactionid")
        private String transactionId; //时间戳到毫秒
        @JsonProperty("name")
        @XStreamAlias("name")
        private String name;          //渠道名称
        @JsonProperty("code")
        @XStreamAlias("code")
        private String code;          //渠道代码
        @JsonProperty("pwd")
        @XStreamAlias("pwd")
        private String pwd;           //渠道密码
        @JsonProperty("rsptime")
        @XStreamAlias("rsptime")
        private String rspTime;       //返回的时间
        @JsonProperty("status")
        @XStreamAlias("status")
        private String status;        //状态编码
        @JsonProperty("rspdesc")
        @XStreamAlias("rspdesc")
        private String rspDesc;       //状态
        @JsonProperty("fileid")
        @XStreamAlias("fileid")
        private String fileId;        //文件id
        @JsonProperty("downloadurl")
        @XStreamAlias("downloadurl")
        private String downloadUrl;   //下载的url
        @XStreamAlias("url")
        private String url;           //文件存储的url
    }

    public void uploadFolder(String newPath, byte[] var2) {

        try {
            if (var2 != null) {
                FileOutputStream output = new FileOutputStream(newPath);
                output.write(var2, 0, var2.length);
                output.flush();
                output.close();
            }
        } catch (Exception e) {
            System.out.println("下载文件内容操作出错");
            e.printStackTrace();

        }
    }
}
